package com.liyuan.help_e.component.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.liyuan.help_e.component.Utils;
import com.liyuan.help_e.dao.AuthorityDao;
import com.liyuan.help_e.dao.RoleDao;
import com.liyuan.help_e.model.Role;
import com.liyuan.help_e.model.User;
import com.liyuan.help_e.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    RoleDao roleDao;
    @Autowired
    AuthorityDao authorityDao;
    @Autowired
    UserService userService;
    @Autowired
    Utils utils;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHeaderStartWith}")
    private String tokenHeaderStartWith;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String authorization = httpServletRequest.getHeader(tokenHeader);
        if (authorization == null) {
            Cookie[] cookies = httpServletRequest.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("token")) {
                        authorization = cookie.getValue();
                        break;
                    }
                }
            }
        }
        if (authorization != null) {
            if (authorization.startsWith(tokenHeaderStartWith)) {
                authorization = authorization.substring(tokenHeaderStartWith.length());
            }
            String username = JWT.decode(authorization).getAudience().get(0);
            User user = userService.selectUserByUsername(username);
            Role role = roleDao.selectRoleById(user.getRole().getId());
            String[]authorities =authorityDao.selectAuthoritiesByRoleId(user.getRole().getId());
            Collection<GrantedAuthority> authorities_ = new ArrayList<>();
            user.getRole().setName(role.getName());
            user.getRole().setAuthorities(authorities_);
            for(String authority:authorities){
                authorities_.add(new SimpleGrantedAuthority(authority));
            }
            user.getRole().setName(role.getName());
            user.getRole().setAuthorities(authorities_);
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            try {
                jwtVerifier.verify(authorization);
            }catch (Exception e){
//                token过期就删除
                Cookie cookie = new Cookie("token", "");
                cookie.setMaxAge(0);
                httpServletResponse.addCookie(cookie);
                e.printStackTrace();
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
